package com.nut.spp.util;

import com.nut.spp.common.Result;
import com.nut.spp.enums.SmsEnum;
import com.nut.spp.redis.RedisClient;
import com.nut.spp.redis.RedisKeys;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 验证码校验工具
 */
@Component
public class CodeValidateUtil {

    @Autowired
    private RedisClient redisClient;

    public Result validateImgCode(String uuid, String code) {
        String key = RedisKeys.getImgCodeKey(uuid);
        return validate(key, code);
    }

    public Result validateSmsCode(String mobile, SmsEnum smsEnum, String code) {
        String key = RedisKeys.getSmsCodeKey(mobile, smsEnum);
        return validate(key, code);
    }

    private Result validate(String key, String code) {
        Object object = redisClient.get(key);

        redisClient.delete(key);

        if (object == null) {
            return Result.fail("验证码不存在或已过期");
        }
        if (!object.toString().equals(code)) {
            return Result.fail("验证码错误");
        }
        return Result.ok();
    }

}
